<?php
namespace Weixin\Controller;
use Think\Controller;
class IndexController extends Controller {
public function _initialize(){
	header("content-type:text/html;charset=utf-8");
	//1将 timestamp ,nonce ,token 按字典排序
		$timestamp=$_GET['timestamp'];
		$nonce   =$_GET['nonce'];
		$token= 'yuntai2016';
		$signature=$_GET['signature'];
		$array=array($timestamp,$nonce,$token);
		sort($array);
		//2将排序后的三个参数拼接用sha1 加密
		$tmpstr=implode('',$array);
		$tmpstr=sha1($tmpstr);
		//3将加密后的字符创鱼signature对比判断是否来自微信
		if ($tmpstr==$signature) {
			echo $_GET['echostr'];
			exit;
		}
}
/*
$url 接口url string
$type 请求类型 string
$res 返回数据类型 string
$arr post 请求参数 string
*/
function http_curl($url,$type="get",$res="json",$arr)
{
	header("content-type:text/html;charset=utf-8");
	// 初始化url
	$ch=curl_init();
	// 设置curl的参数
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	if ($type == "post") {
		curl_setopt($ch,CURLOPT_POST,1);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$arr);
	}
	// 采集
	$output=curl_exec($ch);
	// 4关闭
	curl_close($ch);
	if ($res=='json') {
		if (curl_errno($ch)) {
			return curl_error($ch);
		}else{
			return json_decode($output,true);
		}
		
	}
}
// 全局 accessToken
//    public function getWxAccessToken1()
// {
	// 	$appid='wx770f9d3da4b072d4';
	// 	$appsecret="5d9b1fde1c7913522ef2ab52c3b6236c";
	// 	// 请求地址
	// 	 $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
		// 		// 初始化url
		// 		$ch=curl_init();
		// 		// 设置curl的参数
		// 		curl_setopt($ch,CURLOPT_URL,$url);
		// 		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		// 		// 采集
		// 		 $res=curl_exec($ch);
		// 		// 4关闭
		// 		curl_close($ch);
	// 	if(curl_error($ch)){
		// 		dump(curl_error($ch));
		// 		}
		// 		$arr=json_decode("$res",true);

//     echo "<pre>";
	// print_r ($arr);
	// 	echo "</pre>";
// }
// 获取微信服务器
// public function getServerIp()
// {
// 	$accssToken="sdk9NA5OA5KPCdHw4f2kAAbIIRAenN4vqAv5vwFgrlTcFWDI0BJ9stzTqsduAXPwxhNzc06AKRHF76GO5waSKAkKcMPFzcqQU67OKOe6Hch2XdkpdY9MHZ5HelN8oafnNHVjAAAICQ";
// 	$url="https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=".$accssToken;
// 	// 初始化url
// 	$ch=curl_init();
// 	// 设置curl的参数
// 	curl_setopt($ch,CURLOPT_URL,$url);
// 	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// 	// 采集
// 	$res=curl_exec($ch);
// 	// 4关闭
// 	curl_close($ch);
// if(curl_error($ch)){
// 	dump(curl_error($ch));
// 	}
// 	$arr=json_decode("$res",true);

//     echo "<pre>";
// 	print_r ($arr);
// 	echo "</pre>";
// }
// 返回access_token
public function getWxAccessToken()
{

// 将access_token存入session
	if ($_SESSION['access_token']&&$_SESSION['expire_time']>time()) {
		return $_SESSION['access_token'];
	}else{
		// 如果access_token不存在重新获取
	$appid='wx770f9d3da4b072d4';
	$appsecret="5d9b1fde1c7913522ef2ab52c3b6236c";
	// 请求地址
	$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
	$res=$this->http_curl($url,'get');
	$access_token=$res['access_token'];
	$_SESSION['access_token']=$access_token;
	$_SESSION['expire_time']=time()+7000;  
	return $access_token;
	}
}
// 自定义菜单
public function defineItem()
{
	header("content-type:text/html;charset=utf-8");
	//创建微信菜单
	// 目前微信接口的条用方式都是通过curl post/get方式
  echo $access_token=$this->getWxAccessToken();
	
	$url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
	$postArr=array(
		'button'=>array(
			array(
				'name'=>urlencode('公社大门'),
				'sub_button'=>array(
					array(
					'name'=>urlencode('社区主页'),
					'type'=>'view',
					'url'=>'http://hubao.ynten.com',
						),//第一个二级菜单
					// array(
					// 	'name'=>urlencode('精彩活动'),
					// 	'type'=>'view',
					// 	'url'=>'http://www.baidu.com',
					// 	),//第二个二级菜单
					 array(
						'name'=>urlencode('个人中心'),
						'type'=>'view',
						'url'=>'http://hubao.ynten.com/Weixin/Index/getBaseInfo',
						),//第二个二级菜单
							),
				'type'=>'click',
				'key'=>'itme1',
			),//第一个一级菜单
			array(
				'name'=>urlencode('领取福利'),
				'type'=>'view',
				'url'=>'http://hubao.ynten.com/Member',
				),//第二个一级菜单
			array(
					'name'=>urlencode('了解公社'),
					'type'=>'view',
					'url'=>'http://hubao.ynten.com/Member',
			),//第三个一级菜单
			)
		);
	   
  $postJson=urldecode(json_encode($postArr)); 
	$res=$this->http_curl($url,'post','json',$postJson);
	var_dump($res);

   
}

public  function getBaseInfo()
        {
            //获取code
            $appid='wx770f9d3da4b072d4';
            $redirect_uri="http://hubao.ynten.com/Weixin/Index/getUserOpenId";
            $url=urldecode("https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect");
                 header("location:".$url);
           
        }
      public  function getUserOpenId()
        {
            //获取到网页授权的access_token;
            $appid='wx770f9d3da4b072d4';
            $appsecret="5d9b1fde1c7913522ef2ab52c3b6236c";
            $code=I("get.code");
            $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=$code&grant_type=authorization_code ";
            //拉取用户openid
			$res=$this->http_curl($url,'get');
			$access_token=$res['access_token'];
			$openid=$res["openid"];
   			$url="https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN ";
			$res=$this->http_curl($url);	   
				$user=M("User");
				$data["openid"]=$res["openid"];
				$data['username']=$res['nickname'];
				$data['sex']=$res['sex'];
				$data['createtime']=date("Y-m-d H:i:s",time());
				$data["tsrc"]=$res['headimgurl'];	 
				$OpenidArr=$user->where("openid='{$res["openid"]}'")->find();
				    
			// if (!empty($OpenidArr)) {
			// 	$u=$OpenidArr['id'];
			// 	$_SESSION['user']=$u;
			// 	 $this->redirect("http://hubao.ynten.com/Member/index");
			// }else{
			// 	if ($_SESSION['tel']!="") {
			// 		if (!empty($data)) {
			// 	     $data['tel']=$_SESSION['tel'];
			// 	     $data['yid']=$_SESSION['yid'];
			// 	     $data=array_filter($data);
			// 		 $u=$user->add($data);
			// 		 $_SESSION['user']=$u;
			// 		 $Qian=M("Qianbao");
			// 		 $Ua['uid']=$u;
			// 		 $Qian->add($Ua);
			// 		 unset($_SESSION['mobile']);
			// 		 unset($_SESSION['yid']);
			// 		 $this->redirect("http://hubao.ynten.com/Yaoqing/info");	
			// 	     }
			// 		}else{
			// 			$data=array_filter($data);
			// 	if (!empty($data)) {
			// 		 $u=$user->add($data);
			// 		 $_SESSION['user']=$u;
			// 		 $Qian=M("Qianbao");
			// 		 $Ua['uid']=$u;
			// 		 $Qian->add($Ua);
			// 		$this->redirect("http://hubao.ynten.com/Member/index");
			// 		}
			// 	}

			// }
		}

		//获取JsApiTickt
		public function getJsApiTickt()
{
	// 如果session中保存有效的 jsapi_ticket
	if ($_SESSION['jsapi_ticket_expire_time']>time() && $_SESSION['jsapi_ticket']) {
		$jsapi_ticket=$_SESSION['jsapi_ticket'];
	}else{
		$access_token=$this->getWxAccessToken();
	$url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
	$res=$this->http_curl($url);
	$jsapi_ticket=$res['ticket'];
	$_SESSION['jsapi_ticket']=$jsapi_ticket;
	$_SESSION['jsapi_ticket_expire_time']=time()+7000;
	}
	return $jsapi_ticket;


}
// 获取16伪随码
public function getRandCode()
{
	$tmpstr='';
	$array = array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9");
	$max=count($array);
	for ($i=1; $i < 16; $i++) { 
		$key=$tmpstr.=mt_rand(1,$max-1);
		$tmpstr.=$array[$key];

	}
	return $tmpstr;
}


	   	//短信	
  public function share()
	   {
		// 获取jsapi_ticket
		echo $jsapi_ticket=$this->getJsApiTickt();
		$timestamp=time();
		$noncestr=$this->getRandCode();
		$url='http://hubao.ynten.com/weixin/Index/share';
		$signature='jsapi_ticket='.$jsapi_ticket.'&noncestr='.$noncestr.'&timestamp='.$timestamp.'&url='.$url;
		$signature=sha1($signature);
		$this->timestamp=$timestamp;
		$this->noncestr=$noncestr;
		$this->signature=$signature;

		$this->display('Home@Yaoqing/index');
	}

	public  function getInfo()
        {
            //获取code
            $appid='wx770f9d3da4b072d4';
            $redirect_uri="http://hubao.ynten.com/Weixin/Index/getUserId";
            $url=urldecode("https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect");
                 header("location:".$url);
           
        }

	      public  function getUserId()
        {
            //获取到网页授权的access_token;
            $appid='wx770f9d3da4b072d4';
            $appsecret="5d9b1fde1c7913522ef2ab52c3b6236c";
            $code=I("get.code");
            $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=$code&grant_type=authorization_code ";
            //拉取用户openid
			$res=$this->http_curl($url,'get');
			$access_token=$res['access_token'];
			$openid=$res["openid"];
			$url="https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN ";
			$res=$this->http_curl($url);	
				$user=M("User");
				$data["openid"]=$res["openid"];
				$data['username']=$res['nickname'];
				$data['sex']=$res['sex'];
				$data['createtime']=date("Y-m-d H:i:s",time());
				$data["tsrc"]=$res['headimgurl'];	 

              $OpenidArr=$user->where("openid='{$res["openid"]}'")->find(); 

			if ($OpenidArr['openid']!='') {
				 $_SESSION['user']=$OpenidArr['id'];
				$this->redirect("http://hubao.ynten.com/Yaoqing/index");
				    // echo "<script>
				    //         alert('您已经注册过了');
				    //         history.go(-1);
				    //       </script>";
				          die;
			}
				if (!empty($data)) {
					 $u=$user->add($data);
					 $_SESSION['user']=$u;
					 $Qian=M("Qianbao");
					 $Ua['uid']=$u;
					 $Qian->add($Ua);
					$this->redirect("http://hubao.ynten.com/Yaoqing/info");
				}
					
		}


}